package cc.sjfx.sharedoc.activity.user;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;

import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;

import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.bmob.Examination;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.dialog.ExamFilterDialog;
import cc.sjfx.sharedoc.fragment.BasicFragment;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cc.sjfx.sharedoc.widget.view.CircleImaegeView;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class UserFragment extends BasicFragment implements OnClickListener {
	private CircleImaegeView icoImg;
	// private ImageView bgImg;
	private ImageView sexImg;
	private TextView nickText;
	private TextView signText;
	private TextView pubNumText;
	private TextView answerNumText;
	private TextView collectNumText;
	private String fileName;
	private RelativeLayout myShareLayout;
	private RelativeLayout goodAnswerLayout;
	private RelativeLayout myCollectionLayout;
	protected static final int REQUEST_CODE_CAMERA = 1;
	protected static final int REQUEST_CODE_PHOTO = 2;
	protected static final int REQUEST_CODE_PHOTO_DEAL = 3;
	File f;
	ExamFilterDialog examFilterDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_user, container, false);
		init(view);
		if (UserCache.user.getIcoName() == null) {

		} else {
			setIco();
		}
		setCount();
		return view;
	}

	private void init(View view) {
		// TODO Auto-generated method stub
		icoImg = (CircleImaegeView) view.findViewById(R.id.icoImg);
		// bgImg = (ImageView) view.findViewById(R.id.bgImg);
		sexImg = (ImageView) view.findViewById(R.id.sexImg);
		nickText = (TextView) view.findViewById(R.id.nickText);
		signText = (TextView) view.findViewById(R.id.signText);
		pubNumText = (TextView) view.findViewById(R.id.publishText);
		answerNumText = (TextView) view.findViewById(R.id.answerText);
		collectNumText = (TextView) view.findViewById(R.id.collectText);
		myShareLayout = (RelativeLayout) view.findViewById(R.id.myShareRL);
		goodAnswerLayout = (RelativeLayout) view
				.findViewById(R.id.goodAnswerRL);
		myCollectionLayout = (RelativeLayout) view
				.findViewById(R.id.myCollectionRL);
		myShareLayout.setOnClickListener(this);
		goodAnswerLayout.setOnClickListener(this);
		myCollectionLayout.setOnClickListener(this);
		icoImg.setOnClickListener(this);
		nickText.setOnClickListener(this);
		sexImg.setOnClickListener(this);
		signText.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.icoImg:
			AlertDialog.Builder builder = new Builder(getActivity());
			builder.setTitle("上传方式").setPositiveButton("拍照",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							openCamera();
							// cropPhoto();
						}
					});
			builder.setNegativeButton("相册",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							pickUpPhoto();
						}
					});
			builder.show();
			break;
		case R.id.myShareRL:
			getMyShare();
			break;
		case R.id.goodAnswerRL:
			MToast.show(context, "暂无");
			break;
		case R.id.myCollectionRL:
			getCollect();
			break;
		default:
			break;
		}
	}

	private void getCollect() {
		// TODO Auto-generated method stub
		List<String> list = UserCache.user.getCollectList();
		List<BmobQuery<Examination>> queries = new ArrayList<BmobQuery<Examination>>();
		for (String s : list) {
			BmobQuery<Examination> l = new BmobQuery<Examination>();
			l.addWhereEqualTo("objectId", s);
			queries.add(l);
		}
		BmobQuery<Examination> query = new BmobQuery<Examination>();
		query.or(queries);
		query.setLimit(20);
		query.findObjects(context, new FindListener<Examination>() {

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(List<Examination> arg0) {
				// TODO Auto-generated method stub
				examFilterDialog = new ExamFilterDialog(context);
				examFilterDialog.addListData(arg0);
				examFilterDialog.show();
			}
		});
	}

	private void getMyShare() {
		// TODO Auto-generated method stub
		BmobQuery<Examination> query = new BmobQuery<Examination>();
		query.addWhereEqualTo("user", UserCache.user.getUsername());
		query.setLimit(20);
		query.findObjects(context, new FindListener<Examination>() {

			@Override
			public void onSuccess(List<Examination> arg0) {
				// TODO Auto-generated method stub
				examFilterDialog = new ExamFilterDialog(context);
				examFilterDialog.addListData(arg0);
				examFilterDialog.show();
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub
				MToast.show(context, "获取失败");
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE_CAMERA:
			cropPhoto(Uri.fromFile(new File(Environment
					.getExternalStorageDirectory() + "/" + fileName)));
			break;
		case REQUEST_CODE_PHOTO:
			if(data!=null){
				Uri uri = data.getData();
				cropPhoto(uri);
			}
			break;
		case REQUEST_CODE_PHOTO_DEAL:
			if (data != null) {
				doUpload(data);
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void doUpload(Intent data) {
		// TODO Auto-generated method stub
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);
			String path = savaBitmap(photo);
			MLog.i(path);
			if (path.endsWith("jpg") || path.endsWith("png")
					|| path.endsWith("jpeg")) {
				MToast.show(getActivity(), "正在上传");
				BmobProFile.getInstance(getActivity()).upload(path,
						new UploadListener() {

							@Override
							public void onError(int arg0, String arg1) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onSuccess(String arg0, String arg1) {
								// TODO Auto-generated method stub

								userUpdate(arg0, arg1);
							}

							@Override
							public void onProgress(int arg0) {
								// TODO Auto-generated method stub

							}
						});
			}
		}
	}

	private void openCamera() {
		fileName = UserCache.user.getUsername() + System.currentTimeMillis()
				+ ".jpg";
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
				Environment.getExternalStorageDirectory(), fileName)));
		startActivityForResult(intent, REQUEST_CODE_CAMERA);
	}

	private void pickUpPhoto() {
		fileName = UserCache.user.getUsername() + System.currentTimeMillis()
				+ ".jpg";
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, REQUEST_CODE_PHOTO);
	}

	private void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 240);
		intent.putExtra("outputY", 240);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_DEAL);
	}

	private String savaBitmap(Bitmap bitmap) {
		String fname = Environment.getExternalStorageDirectory().getPath()
				+ "/" + fileName;
		f = new File(fname);
		FileOutputStream fOut = null;
		try {
			f.createNewFile();
			fOut = new FileOutputStream(f);
		} catch (Exception e) {
			e.printStackTrace();
		}
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);// 把Bitmap对象解析成流
		try {
			fOut.flush();
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fname;
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				setIco();
				setCount();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void userUpdate(String arg0, String arg1) {
		// TODO Auto-generated method stub
		User user = new User();
		user.setIcoName(arg0);
		user.setIco(arg1);
		user.update(getActivity(), UserCache.user.getObjectId(),
				new UpdateListener() {
					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						MToast.show(getActivity(), "上传成功");
						UserCache.user = BmobUser.getCurrentUser(getActivity(),
								User.class);
						handler.sendEmptyMessage(1);
						f.delete();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						MToast.show(getActivity(), "上传失败");
					}
				});
	}

	protected void setCount() {
		// TODO Auto-generated method stub
		nickText.setText(UserCache.user.getNickName());
		switch (UserCache.user.getSex()) {
		case 0:
			sexImg.setVisibility(View.GONE);
			break;
		case 1:
			sexImg.setImageResource(R.drawable.user_male);
			break;
		case 2:
			sexImg.setImageResource(R.drawable.user_female);
			break;
		default:
			break;
		}
		if (CheckUtils.stringIsNull(UserCache.user.getSign())) {
			signText.setText("设置一个签名吧！");
		} else {
			signText.setText(UserCache.user.getSign());
		}

		pubNumText.setText(UserCache.user.getPublishNum() + "");
		answerNumText.setText(UserCache.user.getAnswerNum() + "");
		collectNumText.setText(UserCache.user.getCollectNum() + "");
	}

	private void setIco() {
		String icoPath = BmobPro.getInstance(getActivity())
				.getCacheDownloadDir() + "/" + UserCache.user.getIcoName();
		File file = new File(icoPath);
		if (file.exists()) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			Bitmap bm = BitmapFactory.decodeFile(icoPath, options);
			icoImg.setImageBitmap(bm);
		} else {
			BmobProFile.getInstance(getActivity()).download(
					UserCache.user.getIcoName(),
					new com.bmob.btp.callback.DownloadListener() {
						@Override
						public void onError(int arg0, String arg1) {
							// TODO Auto-generated method stub
						}

						@Override
						public void onSuccess(String arg0) {
							// TODO Auto-generated method stub
							handler.sendEmptyMessage(1);
						}

						@Override
						public void onProgress(String arg0, int arg1) {
							// TODO Auto-generated method stub

						}
					});
		}

	}
}
